package com.tozed.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import com.tozed.widget.IPEdit;
import com.tozed.widget.TitleBar;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.TextView;

public class EthernetTestActivity extends Base implements OnClickListener, Runnable
{
	private final static int MSG_REFRESH_DATA = 1;
	private final static int MSG_PING_END = 2;
	
	private TitleBar mTitleBar;
	private Button mBtnPass, mBtnFail;
	private IPEdit mIpEdit;
	private Button mBtnStart;
	private TextView mPingInfo;
	private String mRecvData = "";
	private String mIpAddr;
	private boolean mEnableStart = true;
	private boolean mEthIsConnected = false;
	
	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			mEthIsConnected = isEthConnected();
			if (!mEthIsConnected) {
				mRecvData = getString(R.string.str_eth_not_connected);
			} else {
				mRecvData = "";
			}
			mHandler.sendEmptyMessage(MSG_REFRESH_DATA);
		}
	};
	
	private Handler mHandler = new Handler() {
		
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case MSG_REFRESH_DATA:
				mPingInfo.setText(mRecvData);
				break;
			case MSG_PING_END:
				mEnableStart = true;
				break;
			}
		};
	};
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.ethernet_test);
		
		mTitleBar = (TitleBar)findViewById(R.id.title_bar);
		mTitleBar.setTiteText(R.string.str_test_ethernet);
		mTitleBar.hideRightButton();
				
		mBtnPass = (Button)findViewById(R.id.btn_pass);
		mBtnFail = (Button)findViewById(R.id.btn_fail);
		mBtnPass.setOnClickListener(this);
		mBtnFail.setOnClickListener(this);
		
		mIpEdit = (IPEdit)findViewById(R.id.ip_addr);
		mPingInfo = (TextView)findViewById(R.id.ping_info);
		
		mBtnStart = (Button)findViewById(R.id.btnStart);
		mBtnStart.setOnClickListener(this);
		
		IntentFilter filter = new IntentFilter();
		filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		registerReceiver(mBroadcastReceiver, filter);
		
		mEthIsConnected = isEthConnected();
		if (!mEthIsConnected) {
			mRecvData = getString(R.string.str_eth_not_connected);
		} else {
			mRecvData = "";
		}
		mHandler.sendEmptyMessage(MSG_REFRESH_DATA);
	}
	
	public boolean isEthConnected() {
		ConnectivityManager cm = (ConnectivityManager)
				getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);
		
		if (ni.isConnected()) {
			return true;
		} else {
			return false;
		}
	}
	
	public void startPing() {
		mRecvData = "";
		mIpAddr = mIpEdit.getText(this);
		if (mIpAddr != null && mEthIsConnected) {
			if (mEnableStart) {
				mEnableStart = false;
				new Thread(this).start();
			}
		}
	}
	
	@Override
	protected void onDestroy() {
		unregisterReceiver(mBroadcastReceiver);
		super.onDestroy();
	}
	
	public NetworkInfo getNetworkState() {
		ConnectivityManager cm;
		NetworkInfo ni = null;
		
		cm = (ConnectivityManager)
				getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cm != null) {
			ni = cm.getActiveNetworkInfo();
		}
		
		return ni;
	}
	
	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
		case R.id.btn_pass:
			Intent intent = new Intent();
			intent.putExtra("KEY_TEST_STATUS", 1);
			setResult(RESULT_OK, intent);
			finish();
			break;
			
		case R.id.btn_fail:
			Intent intent2 = new Intent();
			intent2.putExtra("KEY_TEST_STATUS", 0);
			setResult(RESULT_OK, intent2);
			finish();
			break;
			
		case R.id.btnStart:
			mIpEdit.clearFocus();
			mBtnStart.requestFocus();
			InputMethodManager imm = (InputMethodManager)
					getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
			startPing();
			break;
			
		default:
			break;
		}
	}

	@Override
	public void run() {
		Process process = null;
		BufferedReader br = null;
		
		try {
			process = new ProcessBuilder()
							.command("/system/bin/ping", "-c 4", mIpAddr)
							.redirectErrorStream(true)
							.start();
			
			InputStream is = process.getInputStream();
			br = new BufferedReader(new InputStreamReader(is));
			
			String str;
			while ((str = br.readLine()) != null) {
				mRecvData += str + "\n";
				mHandler.sendEmptyMessage(MSG_REFRESH_DATA);
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (process != null) {
				process.destroy();
			}
			
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		mHandler.sendEmptyMessage(MSG_PING_END);
	}
}
